﻿using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Text;
using System.Runtime.Serialization.Formatters.Binary;

namespace ErrorLogger
{
    public class ErrorLogSerializer<T>
    {
        public byte[] Serialize(T item)
        {

            MemoryStream inStream = new MemoryStream();
            MemoryStream outStream = new MemoryStream();
            BinaryFormatter bf = new BinaryFormatter();
            byte[] bytes = null;
            try
            {
                bf.Serialize(inStream, item);
                GZipStream gZipStream = new GZipStream(outStream, CompressionMode.Compress, false);
                gZipStream.Write(inStream.GetBuffer(), 0, inStream.GetBuffer().Length);
                bytes = outStream.ToArray();
            }
            catch (Exception ex)
            {
                
                
            }
            finally
            {
                inStream.Close();
                outStream.Close();
            }
            return bytes;
        }
        public T Deserialize(byte[] item)
        {
            T resultObject = default(T);
            MemoryStream inStream = new MemoryStream();
            MemoryStream outStream = new MemoryStream();
            BinaryFormatter bf = new BinaryFormatter();
            byte[] bytes = null;
            try
            {
                bf.Serialize(inStream, item);
                GZipStream gZipStream = new GZipStream(outStream, CompressionMode.Decompress,false);
                bytes = new byte[outStream.Length];
                outStream.Read(bytes, 0, bytes.Length);

                resultObject = (T) bf.Deserialize(gZipStream);
            }
            catch (Exception ex)
            {


            }
            finally
            {
                inStream.Close();
                outStream.Close();
            }
            return resultObject;
        }

    }
}
